package com.ly.mpayment.rest.up.suhu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
@Path("suhukeji")
public class SuHuRest {
    Logger logger = Logger.getLogger(SuHuRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @Path("callBack")
    @POST
    public String callBack(@RequestBody String data) {
        logger.info("suhu_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            MultiMap multiMap = Util.parceString(data);
            UpOrder order = upOrderService.findById(multiMap.getString("memberOrderId"));
            if(order == null){
                logger.info("订单不存在:"+data);
                return "订单不存在";
            }
            final UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
            if(upShopInfo == null){
                logger.info("渠道用户不存在:"+data);
                return "failt";
            }
            //code=*rechargeOrderId=*memberOrderId=*rechargeAccount=*productId=*faceValue=*signkey=*
            if(!multiMap.getString("sign").equalsIgnoreCase(MD5.md5(
                    "code="+multiMap.getString("code")+"rechargeOrderId="+
                            multiMap.getString("rechargeOrderId")+"memberOrderId="+
                            multiMap.getString("memberOrderId")
                            +"rechargeAccount="+   multiMap.getString("rechargeAccount")
                            +"productId="+
                            multiMap.getString("productId")+"faceValue="+
                            multiMap.getString("faceValue")
                            +"signkey="+upShopInfo.getUpkey()))){
                logger.info("签名错误:"+data);
                return "failt";
            }

            if (order != null && multiMap.getString("code").equals("201") && order.getStatus() == Config.status[0]) {
                order.setRemark(multiMap.containsKey("supplyCert") ? multiMap.getString("supplyCert")
                        : multiMap.getString("msg"));
                RechargeRest.successUpOrder.add(order);
                return "ok";
            } else if (order != null && order.getStatus() == Config.status[0] &&
                    (multiMap.getString("code").equals("202") ||
                     multiMap.getString("code").equals("203") ||
                     multiMap.getString("code").equals("204"))) {
                order.setRemark(multiMap.getString("msg"));
                RechargeRest.failtUpOrder.add(order);
                return "ok";
            } else {
                this.upOrderService.addOrderMsg(order,multiMap.getString("msg"));
                logger.info("suhu_not_found_order:" + multiMap.getString("memberOrderId") + "," + (order == null ? "" : order.getUpphonenum()));
            }
        }
        return "0";
    }


    /**
     * 订单提交
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject data = new JSONObject();
        data.put("memberId", shop.getAppId());
        data.put("productId", order.getUpShopPro().getProductCode());
        data.put("memberOrderId", order.getUporderuuid());
        data.put("rechargeAccount", order.getUpphonenum());
        data.put("faceValue", order.getUpShopPro().getUpfacevalue());
        //memberId=*productId=*memberOrderId=*rechargeAccount=*faceValue=*signkey=*
        data.put("sign", MD5.md5("memberId="+shop.getAppId()+"productId="+
                order.getUpShopPro().getProductCode()+"memberOrderId="+order.getUporderuuid()
                +"rechargeAccount="+order.getUpphonenum()+"faceValue="+ order.getUpShopPro().getUpfacevalue()
                +"signkey="+shop.getUpkey()));

        String result = HttpClient.postUrlFrom(shop.getOrderCommitAddress(), StringSort.jsonToString(data));
        logger.info("commitOrder_suhu:" + result + ":" + StringSort.jsonToString(data));
        if (!StringUtils.isBlank(result)) {
            try{
                JSONObject json = JSONObject.parseObject(result);
                if (json.containsKey("code") && json.getString("code").equals("100")) {
                    this.upOrderService.updateUpOrderMsg(order,json.getString("rechargeOrderId"),json.containsKey("msg") ?
                            json.getString("msg") : "");
                } else if (json.containsKey("code") && errorCode.contains(json.getString("code"))){
                    order.setRemark(json.getString("msg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.addOrderMsg(order, json.getString("code"));
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrder(order, "");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    Set<String> errorCode = new HashSet<String>(){{
        add("101");
        add("102");
        add("103");
        add("104");
        add("105");
        add("106");
        add("107");
        add("108");
        add("109");
    }};

    /**
     * 订单查询
     *
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("memberOrderId", upOrder.getUporderuuid());
        data.put("memberId", shopInfo.getAppId());
        data.put("requestDate", DateUtils.getNowDateToString());
        data.put("sign", MD5.md5("memberId="+
                shopInfo.getAppId()+"rechargeOrderId=memberOrderId="+
                upOrder.getUporderuuid()+"requestDate="+data.getString("requestDate")+"signkey="+shopInfo.getUpkey()));

        String result = HttpClient.postUrlFrom(shopInfo.getOrderStatusAddress(), StringSort.jsonToString(data));
        logger.info("suhuqueryOrder:" + StringSort.jsonToString(data) + ":" + result);
        if (!StringUtils.isBlank(result)) {
            try {
                JSONObject items  = JSONObject.parseObject(result);
                logger.info("queryOrder_suhu_json:" + items);
                if (items.containsKey("result") && items.getString("status").equals("1")) {
                    UpOrder order = upOrderService.findById(items.getJSONArray("result").getJSONObject(0).getString("memberOrderId"));
                    if (order != null && items.getJSONArray("result").getJSONObject(0).getString("code").equals("201") && order.getStatus() == Config.status[0]) {
                        order.setRemark( items.getJSONArray("result").getJSONObject(0).containsKey("supplyCert") ? items.getJSONArray("result").getJSONObject(0).getString("supplyCert") :
                                items.getJSONObject("result").getString("msg"));
                        RechargeRest.successUpOrder.add(order);
                    } else if (order != null && order.getStatus() == Config.status[0] &&
                            (items.getJSONArray("result").getJSONObject(0).getString("code").equals("202") ||
                                    items.getJSONArray("result").getJSONObject(0).getString("code").equals("203") ||
                                    items.getJSONArray("result").getJSONObject(0).getString("code").equals("204")) ) {
                        order.setRemark(items.getJSONArray("result").getJSONObject(0).getString("msg"));
                        RechargeRest.failtUpOrder.add(order);
                    } else {
                        this.upOrderService.addOrderMsg(order,items.getString("msg"));
                        logger.info("suhu_not_found_order:" + order.getUpphonenum());
                    }
                } else if(items.containsKey("result") && items.getString("status").equals("2")) {
                    //logger.info("suhu_not_found_order:" + upOrder.getUpphonenum());
                    upOrder.setRemark(items.getString("msg"));
                    RechargeRest.failtUpOrder.add(upOrder);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
